import cartlist from './cart-mock-data.js'
export default {
	namespaced: true,
	state() {
		return {
			cartList: [
				// ...cartlist  //模拟购物车数据包
			],
			popShow:false,  //控制规格遮罩
			popData:null,   //存放弹窗组件数据
			editIdx:-1   //标记新增、编辑
		}
	},
	getters:{
		allInfo(state){
			console.log('购物车getters执行了');
			let {cartList} = state
			let allPrice = 0
			let allCheck = true  //全选状态
			cartList.forEach(item=>{
				if(item.ischeck){
					allPrice+=item.list[item.dropIdx].price*item.num
				}
				if(!item.ischeck){
					allCheck = false
				}
			})
			uni.setStorage({  //观察数据变化，更新本地存储
				key:'cartList',
				data:state.cartList
			})
			return {
				allPrice,
				allCheck
			}
		}
	},
	mutations:{
		cartPopShowMut(state,bool){
			state.popShow = bool
		},
		cartPopDataMut(state,{cakeObj,editIdx}){ //设置弹窗数据
			state.popData = cakeObj
			state.editIdx = editIdx
		},
		cartAddMut(state,cartObj){ //新增购物车
			console.log(state.editIdx);
			let {editIdx} = state
			let {cartList} = state
			//编辑
			if(editIdx!==-1){ 
				cartList[editIdx] = cartObj
				state.cartList = [...cartList]
				return
			}
			//新增已有商品
			for(let i=0;i<cartList.length;i++){
				let {id,dropIdx} = cartList[i]
				if(id==cartObj.id&&dropIdx==cartObj.dropIdx){
					console.log('修改数量');
					state.cartList[i].num+=cartObj.num
					return
				}
			}
			//新增新商品
			cartObj.ischeck = true
			state.cartList.push(cartObj)
		},
		cartInitMut(state,list){  //初始化状态机数据
			state.cartList = list
		},
		cartCheckMut(state,idx){ //单选
			state.cartList[idx].ischeck = !state.cartList[idx].ischeck
		},
		cartAllCheckMut(state,bool){ //全选控制单选
			state.cartList.forEach(item=>{
				item.ischeck = !bool
			})
		},
		cartDelMut(state,idx){ //删除
			state.cartList.splice(idx,1)
		}
	}
}
